<template>
  <div class="model-creator">
    <el-form
      ref="formRef"
      :model="modelForm"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="模型名称" prop="name">
        <el-input
          v-model="modelForm.name"
          placeholder="请输入模型名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="模型类型" prop="model_type">
        <el-select
          v-model="modelForm.model_type"
          placeholder="选择模型类型"
          @change="handleTypeChange"
          style="width: 100%"
        >
          <el-option
            v-for="type in modelTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          >
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>{{ type.label }}</span>
              <el-tag size="small" type="info">{{ type.category }}</el-tag>
            </div>
            <div style="font-size: 12px; color: #999; margin-top: 2px;">
              {{ type.description }}
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 显示选中模型类型的详细信息 -->
      <el-form-item v-if="selectedModelType" label="模型说明">
        <el-alert
          :title="selectedModelType.label"
          :description="selectedModelType.business_value"
          type="info"
          show-icon
          :closable="false"
        />
      </el-form-item>

      <el-form-item label="算法选择" prop="algorithm">
        <el-select
          v-model="modelForm.algorithm"
          placeholder="选择算法"
          :disabled="!modelForm.model_type"
          @change="handleAlgorithmChange"
          style="width: 100%"
        >
          <el-option
            v-for="algo in availableAlgorithms"
            :key="algo.value"
            :label="algo.label"
            :value="algo.value"
          >
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>{{ algo.label }}</span>
              <div>
                <el-tag size="small" :type="getComplexityType(algo.complexity)">
                  {{ getComplexityLabel(algo.complexity) }}
                </el-tag>
                <el-tag size="small" type="success" style="margin-left: 4px;">
                  {{ algo.accuracy }}
                </el-tag>
              </div>
            </div>
            <div style="font-size: 12px; color: #999; margin-top: 2px;">
              {{ algo.description }} · 训练时间: {{ algo.training_time }}
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 数据集选择 -->
      <el-form-item label="数据集" prop="dataset">
        <el-select
          v-model="modelForm.dataset"
          placeholder="选择数据集"
          :disabled="!modelForm.model_type"
          style="width: 100%"
        >
          <el-option
            v-for="dataset in availableDatasets"
            :key="dataset.value"
            :label="dataset.label"
            :value="dataset.value"
          >
            <div>{{ dataset.label }}</div>
            <div style="font-size: 12px; color: #999; margin-top: 2px;">
              {{ dataset.description }}
            </div>
            <div style="font-size: 11px; color: #666; margin-top: 2px;">
              特征: {{ dataset.features.join(', ') }}
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="模型描述" prop="description">
        <el-input
          v-model="modelForm.description"
          type="textarea"
          :rows="4"
          placeholder="请输入模型描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 训练参数配置 -->
      <el-collapse v-model="activeCollapse">
        <el-collapse-item title="训练参数配置" name="advanced">
          <div v-if="Object.keys(modelForm.training_params).length > 0">
            <el-row :gutter="20">
              <el-col
                v-for="(value, key) in modelForm.training_params"
                :key="key"
                :span="12"
              >
                <el-form-item :label="getParamLabel(key)">
                  <el-input-number
                    v-if="typeof value === 'number'"
                    v-model="modelForm.training_params[key]"
                    :min="getParamMin(key)"
                    :max="getParamMax(key)"
                    :step="getParamStep(key)"
                    :precision="getParamPrecision(key)"
                    style="width: 100%"
                  />
                  <el-switch
                    v-else-if="typeof value === 'boolean'"
                    v-model="modelForm.training_params[key]"
                    active-text="启用"
                    inactive-text="禁用"
                  />
                  <el-input
                    v-else
                    v-model="modelForm.training_params[key]"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-else class="no-params">
            <el-empty description="请先选择模型类型和算法" />
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="$emit('cancel')">取消</el-button>
      <el-button type="primary" @click="handleSave">创建模型</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getModelTypes, getModelAlgorithms, getModelDatasets, getModelDefaultConfig, getDefaultParams } from '@/api/models'

// Emits
const emit = defineEmits(['cancel', 'save'])

// 响应式数据
const formRef = ref(null)
const activeCollapse = ref([])
const modelTypes = ref([])
const availableAlgorithms = ref([])
const availableDatasets = ref([])
const loading = ref(false)

// 表单数据
const modelForm = ref({
  name: '',
  model_type: '',
  algorithm: '',
  dataset: '',
  description: '',
  training_params: {}
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '模型名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  model_type: [
    { required: true, message: '请选择模型类型', trigger: 'change' }
  ],
  algorithm: [
    { required: true, message: '请选择算法', trigger: 'change' }
  ],
  dataset: [
    { required: true, message: '请选择数据集', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入模型描述', trigger: 'blur' },
    { min: 10, max: 200, message: '描述长度在 10 到 200 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const selectedModelType = computed(() => {
  return modelTypes.value.find(type => type.value === modelForm.value.model_type)
})

// 从后端加载模型类型
const loadModelTypes = async () => {
  try {
    const response = await getModelTypes()
    if (response.success) {
      modelTypes.value = response.data.model_types
    } else {
      ElMessage.error('获取模型类型失败')
      // 使用默认数据
      modelTypes.value = [
        {
          value: 'churn_prediction',
          label: '用户流失预测',
          description: '预测用户在未来一段时间内流失的概率',
          category: '预测分析',
          business_value: '提升用户留存率，降低获客成本'
        },
        {
          value: 'purchase_prediction',
          label: '购买意向预测',
          description: '预测用户对特定商品或类别的购买意向',
          category: '预测分析',
          business_value: '提升营销转化率，优化推广策略'
        },
        {
          value: 'recommendation',
          label: '商品推荐系统',
          description: '基于用户行为和偏好，提供个性化商品推荐',
          category: '推荐系统',
          business_value: '提升用户体验，增加销售额'
        },
        {
          value: 'user_segmentation',
          label: '用户行为分群',
          description: '基于用户行为特征进行智能分群',
          category: '聚类分析',
          business_value: '精准营销，个性化服务'
        }
      ]
    }
  } catch (error) {
    console.error('加载模型类型失败:', error)
    ElMessage.error('加载模型类型失败')
  }
}

// 加载算法列表
const loadAlgorithms = async (modelType) => {
  try {
    const response = await getModelAlgorithms({ model_type: modelType })
    if (response.success) {
      availableAlgorithms.value = response.data.algorithms
    } else {
      availableAlgorithms.value = []
    }
  } catch (error) {
    console.error('加载算法列表失败:', error)
    availableAlgorithms.value = []
  }
}

// 加载数据集列表
const loadDatasets = async (modelType) => {
  try {
    const response = await getModelDatasets({ model_type: modelType })
    if (response.success) {
      availableDatasets.value = response.data.datasets
    } else {
      availableDatasets.value = []
    }
  } catch (error) {
    console.error('加载数据集列表失败:', error)
    availableDatasets.value = []
  }
}

// 加载默认配置
const loadDefaultConfig = async (modelType) => {
  try {
    const response = await getModelDefaultConfig({ model_type: modelType })
    if (response.success) {
      const defaultConfig = response.data.default_config

      // 自动设置默认算法和数据集
      if (defaultConfig.algorithm) {
        modelForm.value.algorithm = defaultConfig.algorithm
      }
      if (defaultConfig.dataset) {
        modelForm.value.dataset = defaultConfig.dataset
      }

      // 加载默认训练参数
      if (defaultConfig.algorithm) {
        await loadDefaultParams()
      }
    }
  } catch (error) {
    console.error('加载默认配置失败:', error)
  }
}

// 加载默认训练参数
const loadDefaultParams = async () => {
  if (!modelForm.value.model_type || !modelForm.value.algorithm) return

  try {
    const response = await getDefaultParams({
      model_type: modelForm.value.model_type,
      algorithm: modelForm.value.algorithm
    })

    if (response.success) {
      modelForm.value.training_params = response.data.params || {}
    }
  } catch (error) {
    console.error('加载默认参数失败:', error)
  }
}

// 方法
const handleTypeChange = async () => {
  // 清空相关选择
  modelForm.value.algorithm = ''
  modelForm.value.dataset = ''
  modelForm.value.training_params = {}

  if (modelForm.value.model_type) {
    // 并行加载算法、数据集和默认配置
    await Promise.all([
      loadAlgorithms(modelForm.value.model_type),
      loadDatasets(modelForm.value.model_type),
      loadDefaultConfig(modelForm.value.model_type)
    ])
  }
}

const handleAlgorithmChange = () => {
  // 加载默认参数
  loadDefaultParams()
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    // 发送数据到父组件
    emit('save', modelForm.value)

    ElMessage.success('模型创建成功')
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    loading.value = false
  }
}

// 辅助函数
const getComplexityType = (complexity) => {
  const typeMap = {
    'low': 'success',
    'medium': 'warning',
    'high': 'danger',
    'very_high': 'danger'
  }
  return typeMap[complexity] || 'info'
}

const getComplexityLabel = (complexity) => {
  const labelMap = {
    'low': '简单',
    'medium': '中等',
    'high': '复杂',
    'very_high': '很复杂'
  }
  return labelMap[complexity] || '未知'
}

// 参数处理辅助函数
const getParamLabel = (key) => {
  const labelMap = {
    'n_estimators': '树的数量',
    'max_depth': '最大深度',
    'min_samples_split': '最小分割样本',
    'min_samples_leaf': '最小叶子样本',
    'learning_rate': '学习率',
    'subsample': '子样本比例',
    'colsample_bytree': '特征子样本比例',
    'C': '正则化参数',
    'max_iter': '最大迭代次数',
    'hidden_layer_sizes': '隐藏层大小',
    'activation': '激活函数',
    'solver': '求解器',
    'alpha': '正则化强度',
    'n_clusters': '聚类数量',
    'init': '初始化方法',
    'n_init': '初始化次数',
    'random_state': '随机种子'
  }
  return labelMap[key] || key
}

const getParamMin = (key) => {
  const minMap = {
    'n_estimators': 1,
    'max_depth': 1,
    'min_samples_split': 2,
    'min_samples_leaf': 1,
    'learning_rate': 0.001,
    'subsample': 0.1,
    'colsample_bytree': 0.1,
    'C': 0.001,
    'max_iter': 1,
    'alpha': 0.0001,
    'n_clusters': 2,
    'n_init': 1,
    'random_state': 0
  }
  return minMap[key] || 0
}

const getParamMax = (key) => {
  const maxMap = {
    'n_estimators': 1000,
    'max_depth': 50,
    'min_samples_split': 20,
    'min_samples_leaf': 10,
    'learning_rate': 1,
    'subsample': 1,
    'colsample_bytree': 1,
    'C': 100,
    'max_iter': 10000,
    'alpha': 1,
    'n_clusters': 20,
    'n_init': 50,
    'random_state': 9999
  }
  return maxMap[key] || 1000
}

const getParamStep = (key) => {
  const stepMap = {
    'learning_rate': 0.001,
    'subsample': 0.1,
    'colsample_bytree': 0.1,
    'C': 0.1,
    'alpha': 0.0001
  }
  return stepMap[key] || 1
}

const getParamPrecision = (key) => {
  const precisionMap = {
    'learning_rate': 4,
    'subsample': 2,
    'colsample_bytree': 2,
    'C': 3,
    'alpha': 4
  }
  return precisionMap[key] || 0
}

// 初始化
onMounted(() => {
  loadModelTypes()
})
</script>

<style scoped>
.no-params {
  text-align: center;
  padding: 20px;
  color: #999;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-select, .el-input {
  width: 100%;
}

.el-alert {
  margin-bottom: 15px;
}

.el-collapse {
  border: none;
}

.el-collapse-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 10px;
}

.el-collapse-item :deep(.el-collapse-item__header) {
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
  padding: 0 20px;
  font-weight: 500;
}

.el-collapse-item :deep(.el-collapse-item__content) {
  padding: 20px;
}

.form-actions {
  margin-top: 30px;
  text-align: right;
}

.form-actions .el-button {
  margin-left: 10px;
}
</style>